"""
@File: user.py
@Project: 约个球
@Author: zhangjian
@Time: 2022.8.22 21:59
@Description: None
"""
from model import db
import datetime
from model.schedule import ScheduleManager
from werkzeug.security import generate_password_hash


class UserManager(db.Model):
    """用户表类"""
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    _password = db.Column("password", db.String(512), nullable=False)
    email = db.Column(db.String(128), nullable=False)
    sex = db.Column(db.Enum("男","女"), nullable=False)
    location_x = db.Column(db.Float, nullable=False)
    location_y = db.Column(db.Float, nullable=False)
    CreateAt = db.Column(db.DateTime, default=datetime.datetime.now())
    # 一对多关系
    schedule = db.relationship("ScheduleManager", backref="userss")

    def keys(self):
        """对类做序列化"""
        return ('username', 'email', 'sex', 'location_x', 'location_y', 'schedules')

    def __getitem__(self, item):
        return getattr(self, item)

    def to_json(self):
        """序列化方式二"""
        return {
            "username": self.username,
            "password": self.password,
            "email": self.email,
            "schedules": self.schedules
        }

    # 属性包装，定义一些属性之前做一些检测，转换，把方法当作属性一样使用
    @property  # -----> password.setter    user.password()——》user.password = self._password
    def password(self):
        return self._password

    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    @classmethod
    def create_user(cls, username, password, email, sex, location_x, location_y):
        user = cls()
        user.username = username
        user.password = password
        user.email = email
        user.sex = sex
        user.location_x = location_x
        user.location_y = location_y
        db.session.add(user)
        db.session.commit()


#API授权表的模型，多对多的关系
app_permission = db.Table("app_permission",
                          db.Column("api_id",db.ForeignKey("api_token.id")),
                          db.Column("permission_id",db.ForeignKey("api_permission.id"))
                          )


class ApiToken(db.Model):
    """api_token表
    存放的是授权密钥，以及授权id"""
    __tablename__ = "api_token"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appid = db.Column(db.String(128), nullable=False)
    secretkey = db.Column(db.String(128), nullable=False)
    # 通过中间表去创建多对多的关系
    manage = db.relationship("ApiPermission", secondary=app_permission, backref="tokens")


class ApiPermission(db.Model):
    """存放的是授权的url"""
    __tablename__ = "api_permission"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    url = db.Column(db.String(128), nullable=False)
    method_type = db.Column(db.String(128), nullable=False)